package com.myFwk.aspect;

import com.baomidou.mybatisplus.extension.api.IErrorCode;
import com.myFwk.model.R;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Title:
 * @Description:
 * @Author: guowl
 * @version： 1.0
 * @Date:2021/8/30
 * @Copyright: Copyright(c)2021 RedaFlight.com All Rights Reserved
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     *
     * 为什么要写全局异常：因为现在都是前后端分离，要返回数据到前端，都会返回json。
     * 此外，代码里面太多try catch，影响代码美观。还有就是对异常进行自定义和统一管理
     */

    /**
     * 1 内部API调用异常
     */
    @ExceptionHandler(ApiException.class)
    public R handlerApiException(ApiException apiException) {
        IErrorCode errorCode = apiException.getErrorCode();
        if (errorCode == null) {
            return R.fail(errorCode);
        }
        return R.fail(apiException.getMessage());
    }

    /**
     * 2.方法参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handlerMethodArgumentNotValidException(MethodArgumentNotValidException exception) {
        BindingResult bindingResult = exception.getBindingResult();
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                return R.fail(fieldError.getField() + fieldError.getDefaultMessage());
            }
        }
        return R.fail(exception.getMessage());
    }

    /**
     * 对象内部使用volidate 没有校验异常
     *
     * @return
     */
    @ExceptionHandler(BindException.class)
    public R handlerBindException(BindException bindException) {
        BindingResult bindingResult = bindException.getBindingResult();
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                return R.fail(fieldError.getField() + fieldError.getDefaultMessage());
            }
        }
        return R.fail(bindException.getMessage());
    }

}
